package com.zx.cloud.file.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: zx-file-service
 * @description:
 * @author: chenxf
 * @create: 2022-01-27 17:26
 **/
public class WordUtil {

    /**
     * 替换段落文本
     *
     * @param document docx解析对象
     * @param textMap  需要替换的信息集合
     */
    public static void changeText(XWPFDocument document, Map<String, String> textMap) {
        //获取段落集合
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            //获取到段落中的所有文本内容
            String text = paragraph.getText();
            //判断此段落中是否有需要进行替换的文本
            if (checkText(text)) {
                List<XWPFRun> runs = paragraph.getRuns();
                for (XWPFRun run : runs) {
                    //替换模板原来位置
                    run.setText(changeValue(run.toString(), textMap), 0);
                }
            }
        }
    }

    /**
     * 判断文本中是否包含$
     *
     * @param text 文本
     * @return 包含返回true, 不包含返回false
     */
    public static boolean checkText(String text) {
        boolean check = false;
        if (text.indexOf("$") != -1) {
            check = true;
        }
        return check;
    }

    /**
     * 匹配传入信息集合与模板
     *
     * @param value   模板需要替换的区域
     * @param textMap 传入信息集合
     * @return 模板需要替换区域信息集合对应值
     */
    public static String changeValue(String value, Map<String, String> textMap) {
        System.out.println("value::"+value+"::");
        String mapKey=value.trim().replace("${","").replace("}","");
        String mapValue=textMap.get(mapKey);
        if(StringUtils.isNotEmpty(mapValue)){
            value ="  "+mapValue+"  ";//value.replace("${"+mapKey+"}",mapValue);
        }
        //模板未匹配到区域替换为空
        if (checkText(value)) {
            value = "";
        }
        return value;
    }

    public static File saveWordFile(String templatePath, String fileName, Map<String, String> replaceMap) {
        InputStream in = null;
        try {
            in = new FileInputStream(templatePath);
            //获取docx解析对象
            XWPFDocument document = new XWPFDocument(in);

            File dest = (new File(fileName)).getCanonicalFile();
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            changeText(document, replaceMap);
            document.write(new FileOutputStream(dest));
            document.close();
            return dest;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args){
        Map<String, String> replaceMap=new HashMap<>();
        LocalDate sDate=LocalDate.now(),eDate=sDate.plusYears(2),signDate=sDate;
        Long leaseTerm= ChronoUnit.YEARS.between(sDate,eDate.plusDays(1));
        replaceMap.put("custName","***科技创新服务有限公司");
        replaceMap.put("address","**高新区育才路188路");
        replaceMap.put("rentArea","600");
        replaceMap.put("leaseTerm",leaseTerm.toString());
        replaceMap.put("sYear",sDate.getYear()+"");
        replaceMap.put("sMonth",sDate.getMonthValue()+"");
        replaceMap.put("sDay",sDate.getDayOfMonth()+"");
        replaceMap.put("eYear",eDate.getYear()+"");
        replaceMap.put("eMonth",eDate.getMonthValue()+"");
        replaceMap.put("eDay",eDate.getDayOfMonth()+"");
        replaceMap.put("signYear",signDate.getYear()+"");
        replaceMap.put("signMonth",signDate.getMonthValue()+"");
        replaceMap.put("signDay",signDate.getDayOfMonth()+"");
        replaceMap.put("yearMoney","10000");
        replaceMap.put("marginMoney","5000");
        WordUtil.saveWordFile("f://wordTemplate.docx","f://wordDemo2.docx",replaceMap);
    }
}
